#include <stdio.h>
#include <timeout_spin_lock.c>

typedef struct __account_t {
	lock_t mut;
	double balance;
} account_t;

// 转账，从 src 账户往 target 账户上转 amt 元
void transfer(account_t *src, 
				account_t *target, 
				double amt) {
	int is_succ = 0;
	while (!is_succ) {
		// 会产生活锁
		if (lock(&src->mut, 200)) {
			if (lock(&target->mut, 200)) {
				if (src->balance > amt) {
		        	src->balance -= amt;
        			target->balance += amt;
   				}
				is_succ = 1;
				unlock(&target->mut);
			}
			unlock(&src->mut);
		}
		
	}
}


int main() {
	account_t src;
	src.balance = 100;
	
	pthread_mutex_init(&src.mut, NULL);


	account_t target;
    target.balance = 100;

	pthread_mutex_init(&target.mut, NULL);

	transfer(&src, &target, 20);

	printf("src 账户余额：%f\n", src.balance);	
	printf("target 账户余额：%f\n", target.balance);	
}
